package com.vdong.restful.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vdong.data.model.Shipper;
import com.vdong.data.model.ShipperApplication;
import com.vdong.data.model.ShipperOrderUser;
import com.vdong.data.model.enums.OrderType;
import com.vdong.data.model.enums.PayType;
import com.vdong.data.model.enums.State;
import com.vdong.data.service.ShipperApplicationService;
import com.vdong.data.service.ShipperOrderUserService;
import com.vdong.data.service.ShipperService;
import com.vdong.restful.api.request.CancelOrderRequest;
import com.vdong.restful.api.request.CommodityRequest;
import com.vdong.restful.api.request.OOrderRequest;
import com.vdong.restful.api.request.OrderRequest;
import com.vdong.restful.api.response.OOrderResponse;
import com.vdong.restful.api.response.OrderResponse;
import com.vdong.restful.api.response.Response;
import com.vdong.restful.service.OrderApiService;
import com.vdong.restful.staticVariable.GlobalStaticVariable;
import com.vdong.supplier.request.supplierbird.*;
import com.vdong.supplier.response.supplierbird.EbusinessCancelOrderResponse;
import com.vdong.supplier.response.supplierbird.EbusinessOOrderResponse;
import com.vdong.supplier.response.supplierbird.EbusinessOrderResponse;
import com.vdong.supplier.response.supplierbird.KdnResponse;
import com.vdong.supplier.service.supplierbird.PostQueryClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderApiServiceImpl implements OrderApiService {

    private Logger logger = LoggerFactory.getLogger(OrderApiServiceImpl.class);

    @Value("${kuaidn.applicationId}")
    private int applicationId;

    @Value("${kuaidn.requestOrderType}")
    private String requestType;

    @Value("${kuaidn.doorTaskType}")
    private String doorTaskType;

    @Value("${kuaidn.cancelOrderType}")
    private String cancelOrderType;

    @Value("${kuaidn.environment}")
    private Integer environment;

    @Autowired
    private ShipperService shipperService;

    @Autowired
    private PostQueryClassService postQueryClassService;
    @Autowired
    private ShipperApplicationService shipperApplicationService;
    //和supplier json bean重复
    @Qualifier("ObjectMapper") 
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ShipperOrderUserService shipperOrderUserService;


    @Override
    public Response downOrder(OrderRequest orderRequest, String key) {

        Shipper shipper = shipperService.findById(orderRequest.getShipperId());
        ShipperOrderUser shipperOrderUser = null;
        if (shipper == null) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "没有匹配的信息");
        } else if (shipper.getPlaceOrder() == State.OFF) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "快递公司不支持该业务");
        } else if (shipper.getPlaceOrderUsersType() == OrderType.ON || shipper.getPlaceOrderUsersType() == OrderType.ONOROFF) {
            shipperOrderUser = shipperOrderUserService.findbyShipperIdAndUserIdAndKey(orderRequest.getShipperId(), orderRequest.getUserId(), key);
            if (shipperOrderUser == null && shipper.getPlaceOrderUsersType() == OrderType.ON) {
                return Response.failMessage(GlobalStaticVariable.VALIDATION, "快递公司需要提供账号密码等信息，请联系快递网点获取");

            }

        }


        ShipperApplication shipperApplication = shipperApplicationService.get(applicationId);
        Receiver receiver = new Receiver();
        receiver.setAddress(orderRequest.getReceiverAddress());
        receiver.setCityName(orderRequest.getReceiverCityName());
        receiver.setMobile(orderRequest.getReceiverMobile());
        receiver.setName(orderRequest.getReceiverName());
        receiver.setProvinceName(orderRequest.getReceiverProvinceName());
        receiver.setCompany(orderRequest.getReceiverCompany());
        receiver.setExpAreaName(orderRequest.getReceiverExpAreaName());
        receiver.setPostCode(orderRequest.getReceiverPostCode());

        Sender sender = new Sender();
        sender.setAddress(orderRequest.getSenderAddress());
        sender.setCityName(orderRequest.getSenderCityName());
        sender.setExpAreaName(orderRequest.getSenderExpAreaName());
        sender.setMobile(orderRequest.getSenderMobile());
        sender.setName(orderRequest.getSenderName());
        sender.setProvinceName(orderRequest.getSenderProvinceName());
        sender.setCompany(orderRequest.getSenderCompany());
        sender.setPostCode(orderRequest.getSenderPostCode());

        List<Commodity> commoditys = new ArrayList<>();
        Commodity commodity;
        for (CommodityRequest commodityRequest : orderRequest.getCommodityRequest()) {
            commodity = new Commodity();
            commodity.setGoodsCode(commodityRequest.getGoodsCode());
            commodity.setGoodsDesc(commodityRequest.getGoodsDesc());
            commodity.setGoodsName(commodityRequest.getGoodsName());
            commodity.setGoodsquantity(commodityRequest.getGoodsquantity());
            commodity.setGoodsVol(commodityRequest.getGoodsVol());
            commodity.setGoodsWeight(commodityRequest.getGoodsWeight());
            commoditys.add(commodity);

        }
        EbusinessOrderRequest ebusinessOrderRequest = new EbusinessOrderRequest();

        if (shipperOrderUser != null) {
            ebusinessOrderRequest.setCustomerPwd(shipperOrderUser.getCustomerPwd());
            ebusinessOrderRequest.setCustomerName(shipperOrderUser.getCustomerName());
            ebusinessOrderRequest.setSendSite(shipperOrderUser.getSendSite());
            ebusinessOrderRequest.setMonthCode(shipperOrderUser.getMonthCode());
        }

        ebusinessOrderRequest.setCommodity(commoditys);
        ebusinessOrderRequest.setCallBack(orderRequest.getCallBack());
        ebusinessOrderRequest.setMemberID(orderRequest.getMemberID());
        ebusinessOrderRequest.setShipperCode(shipper.getCode());
        ebusinessOrderRequest.setLogisticCode(orderRequest.getLogisticCode());
        ebusinessOrderRequest.setOrderCode(orderRequest.getOrderCode());
        ebusinessOrderRequest.setThrOrderCode(orderRequest.getThrOrderCode());

        ebusinessOrderRequest.setPayType(orderRequest.getPayType().ordinal());
        ebusinessOrderRequest.setExpType(orderRequest.getExpType());
        ebusinessOrderRequest.setIsNotice(orderRequest.getIsNotice());
        ebusinessOrderRequest.setCost(orderRequest.getCost());
        ebusinessOrderRequest.setOtherCost(orderRequest.getOtherCost());
        ebusinessOrderRequest.setReceiver(receiver);
        ebusinessOrderRequest.setSender(sender);
        ebusinessOrderRequest.setRemark(orderRequest.getRemark());
        ebusinessOrderRequest.setVolume(orderRequest.getVolume());
        ebusinessOrderRequest.setQuantity(orderRequest.getQuantity());
        ebusinessOrderRequest.setWeight(orderRequest.getWeight());
        ebusinessOrderRequest.setStartDate(orderRequest.getStartDate());
        ebusinessOrderRequest.setEndDate(orderRequest.getEndDate());
        ebusinessOrderRequest.setIsReturnPrintTemplate(orderRequest.getIsReturnPrintTemplate().ordinal() + "");
        ebusinessOrderRequest.setTemplateSize(orderRequest.getTemplateSize());





        EbusinessOrderHandleRequest ebusinessOrderHandleRequest = new EbusinessOrderHandleRequest(ebusinessOrderRequest,
                shipperApplication.getAppid(), requestType, shipperApplication.getAppkey(), "2");

        KdnResponse a = postQueryClassService.EbusinessOrder(ebusinessOrderHandleRequest, environment);
        logger.info("电子面单：order:{}:KdnResponse:{}", orderRequest.toString(), a.toString());
        if (a.getSuccess()) {

            EbusinessOrderResponse e = (EbusinessOrderResponse) a.getResponseParent();
            if (e.getResultCode() != null && e.getResultCode().equals("100")) {

                OrderResponse orderResponse = new OrderResponse();
                orderResponse.setDestinatioCode(e.getOrder().getDestinatioCode());
                orderResponse.setKdnorderCode(e.getOrder().getKDNOrderCode());
                orderResponse.setLogisticCode(e.getOrder().getLogisticCode());
                orderResponse.setOriginCode(e.getOrder().getOriginCode());
                orderResponse.setPrintTemplate(e.getPrintTemplate());
                orderResponse.setShipperCode(shipper.getCode());
                orderResponse.setShipperId(shipper.getId());
                orderResponse.setSubCount(e.getSubCount());
                orderResponse.setSubOrders(e.getSubOrders());
                orderResponse.setSubPrintTemplates(e.getSubPrintTemplates());
                return Response.successBean(orderResponse);
            } else {
                return Response.failMessage(GlobalStaticVariable.VALIDATION, e.getReason());
            }

        } else if (!a.getSuccess()) {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, a.getMessage());
        } else {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, "网络异常");
        }

    }


    /**
     * 预约取件
     *
     * @param oOrderRequest
     * @return
     */
    @Override
    public Response noticeOrder(OOrderRequest oOrderRequest, String key) {

        Shipper shipper = shipperService.findById(oOrderRequest.getShipperId());
        ShipperOrderUser shipperOrderUser = null;
        if (shipper == null) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "没有匹配的信息");
        } else if (shipper.getDoorTask() == State.OFF) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "快递公司不支持该业务");
        } else if (oOrderRequest.getPayType() == PayType.MONTHLY) {
            shipperOrderUser = shipperOrderUserService.findbyShipperIdAndUserIdAndKey(oOrderRequest.getShipperId(), oOrderRequest.getUserId(), key);

            if (shipperOrderUser == null || shipperOrderUser.getMonthCode() == null)
                return Response.failMessage(GlobalStaticVariable.VALIDATION, "支付需要提供月结码，请联系快递网点获取");
        }

        ShipperApplication shipperApplication = shipperApplicationService.get(applicationId);
        Receiver receiver = new Receiver();
        receiver.setAddress(oOrderRequest.getReceiverAddress());
        receiver.setCityName(oOrderRequest.getReceiverCityName());
        receiver.setMobile(oOrderRequest.getReceiverMobile());
        receiver.setName(oOrderRequest.getReceiverName());
        receiver.setProvinceName(oOrderRequest.getReceiverProvinceName());
        receiver.setCompany(oOrderRequest.getReceiverCompany());
        receiver.setExpAreaName(oOrderRequest.getReceiverExpAreaName());
        receiver.setPostCode(oOrderRequest.getReceiverPostCode());

        Sender sender = new Sender();
        sender.setAddress(oOrderRequest.getSenderAddress());
        sender.setCityName(oOrderRequest.getSenderCityName());
        sender.setExpAreaName(oOrderRequest.getSenderExpAreaName());
        sender.setMobile(oOrderRequest.getSenderMobile());
        sender.setName(oOrderRequest.getSenderName());
        sender.setProvinceName(oOrderRequest.getSenderProvinceName());
        sender.setCompany(oOrderRequest.getSenderCompany());
        sender.setPostCode(oOrderRequest.getSenderPostCode());

        List<Commodity> commoditys = new ArrayList<>();
        Commodity commodity;
        for (CommodityRequest commodityRequest : oOrderRequest.getCommodityRequest()) {
            commodity = new Commodity();
            commodity.setGoodsCode(commodityRequest.getGoodsCode());
            commodity.setGoodsDesc(commodityRequest.getGoodsDesc());
            commodity.setGoodsName(commodityRequest.getGoodsName());
            commodity.setGoodsquantity(commodityRequest.getGoodsquantity());
            commodity.setGoodsVol(commodityRequest.getGoodsVol());
            commodity.setGoodsWeight(commodityRequest.getGoodsWeight());
            commoditys.add(commodity);

        }
        String mothCode = null;
        if (shipperOrderUser != null) {
            mothCode = shipperOrderUser.getMonthCode();
        }

        EbusinessOOrderRequest ebusinessOOrderRequest = new EbusinessOOrderRequest(oOrderRequest.getCallBack(), oOrderRequest.getMemberID(), shipper.getCode(),
                oOrderRequest.getLogisticCode(), oOrderRequest.getOrderCode(), mothCode,
                oOrderRequest.getPayType().ordinal(), oOrderRequest.getExpType(), oOrderRequest.getCost(),
                oOrderRequest.getOtherCost(), receiver, sender, oOrderRequest.getRemark(), oOrderRequest.getVolume(),
                oOrderRequest.getQuantity(), oOrderRequest.getWeight(), oOrderRequest.getStartDate(),
                oOrderRequest.getEndDate(), commoditys);

        EbusinessOrderHandleRequest ebusinessOrderHandleRequest = new EbusinessOrderHandleRequest(
                ebusinessOOrderRequest, shipperApplication.getAppid(), doorTaskType, shipperApplication.getAppkey(),
                "2");

        KdnResponse a = postQueryClassService.EbusinessOOrder(ebusinessOrderHandleRequest, environment);
        logger.info("预约取件：order:{}:KdnResponse:{}", oOrderRequest.toString(), a.toString());
        if (a.getSuccess()) {


            EbusinessOOrderResponse e = (EbusinessOOrderResponse) a.getResponseParent();

            System.out.println(e.getResultCode());
            if (e.getResultCode() != null && e.getResultCode().equals("100")) {


                OOrderResponse orderResponse = new OOrderResponse();

                orderResponse.setKdnorderCode(e.getOrder().getKDNOrderCode());
                orderResponse.setLogisticCode(e.getOrder().getLogisticCode());

                orderResponse.setShipperCode(shipper.getCode());
                orderResponse.setShipperId(shipper.getId());
                return Response.successBean(orderResponse);
            } else {
                return Response.failMessage(GlobalStaticVariable.VALIDATION, e.getReason());
            }

        } else if (!a.getSuccess()) {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, a.getMessage());
        } else {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, "网络异常");
        }

    }


    /**
     * 取消订单
     * @param cancelOrderRequest
     * @return
     */
    @Override
    public Response cancelOrder(CancelOrderRequest cancelOrderRequest) {
        Shipper shipper = shipperService.findById(cancelOrderRequest.getShipperId());

        if (shipper == null) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "没有匹配的信息");
        } else if (shipper.getPlaceOrder() == State.OFF) {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "快递公司不支持该业务查询");
        }
        ShipperApplication shipperApplication = shipperApplicationService.get(applicationId);
        EbusinessCancelOrderRequest ebusinessCancelOrderRequest = new EbusinessCancelOrderRequest(shipper.getCode(),
                cancelOrderRequest.getOrderCode(), cancelOrderRequest.getLogisticCode(),
                cancelOrderRequest.getCustomerName(), cancelOrderRequest.getCustomerPwd());
        EbusinessOrderHandleRequest ebusinessOrderHandleRequest = new EbusinessOrderHandleRequest(
                ebusinessCancelOrderRequest, shipperApplication.getAppid(), cancelOrderType,
                shipperApplication.getAppkey(), "2");
        KdnResponse a = postQueryClassService.EbusinessCancleOrder(ebusinessOrderHandleRequest, environment);
        logger.info("取消电子面单：orderCode：" + cancelOrderRequest.getOrderCode() + ":KdnResponse:" + a.toString());
        if (a.getSuccess()) {

            EbusinessCancelOrderResponse e = (EbusinessCancelOrderResponse) a.getResponseParent();


            if (e.getResultCode() != null && e.getResultCode().equals("100")) {

                return Response.successBean(e.getResultCode());
            } else {
                return Response.failMessage(GlobalStaticVariable.VALIDATION, e.getReason());
            }

        } else if (!a.getSuccess()) {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, a.getMessage());
        } else {
            return Response.failMessage(GlobalStaticVariable.EXCEPTION, "网络异常");
        }
    }

}
